#!/bin/bash

onlyone=$1

export PHD_VAR_network_nic_base="54:52:00"
export PHD_VAR_vm_base="/srv/rhos6-rhel7-vms/rhos6-rhel7-base.img"
export PHD_VAR_vm_vcpu="1"
export PHD_VAR_vm_ram="2048"
export PHD_ENV_nodes1=east-01.lab.bos.redhat.com

cat<<-EOF > /localvms/template.xml
<domain type='kvm'>
  <name>VM_NAME</name>
  <memory>${PHD_VAR_vm_ram}000</memory>
  <currentMemory>${PHD_VAR_vm_ram}000</currentMemory>
  <vcpu>${PHD_VAR_vm_cpus}</vcpu>
  <os>
    <type arch='x86_64' machine='pc'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>restart</on_crash>
  <devices>
    <emulator>/usr/libexec/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/srv/rhos6-rhel7-vms/rhos6-rhel7-base.img'/>
      <target dev='vda' bus='virtio'/>
    </disk>
    <interface type='bridge'>
      <mac address='EXTERNAL_MAC'/>
      <source bridge='ext0'/>
      <model type='virtio'/>
    </interface>
    <interface type='bridge'>
      <mac address='INTERNAL_MAC'/>
      <source bridge='vmnet0'/>
      <model type='virtio'/>
    </interface>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <input type='tablet' bus='usb'/>
    <input type='mouse' bus='ps2'/>
    <graphics type='vnc' port='-1' autoport='yes'/>
  </devices>
</domain>
EOF
sequence=16
lastoct="$(hostname -s | sed -e 's#^[a-z]*-##g' -e 's#^0*##g')"
offset="$(echo ${PHD_ENV_nodes1} | sed -e 's#^[a-z]*-##g' -e 's#^0*##g' -e 's#\..*##')"
for section in lb db rabbitmq memcache glance cinder swift-brick swift neutron nova horizon heat mongodb ceilometer qpid node keystone; do

  dobuild=0
  if [ -z $onlyone ]; then
      dobuild=1
  elif [ $onlyone = $section ]; then
      dobuild=1
  fi
    
  if [ $dobuild = 1 ]; then
    cd /localvms/
    target=rhos6-${section}$(( ${lastoct} - ${offset} ))
    virsh destroy  $target > /dev/null 2>&1
    virsh undefine $target > /dev/null 2>&1
    cp template.xml ${target}.xml
    sed -i.sed s#VM_NAME#${target}#g ${target}.xml
    sed -i.sed s#EXTERNAL_MAC#${PHD_VAR_network_nic_base}:0${lastoct}:00:${sequence}#g ${target}.xml
    sed -i.sed s#INTERNAL_MAC#${PHD_VAR_network_nic_base}:0${lastoct}:01:${sequence}#g ${target}.xml
    sed -i.sed s:source\ file.*\/:source\ file=\'/localvms/${target}.cow\'\/:g ${target}.xml
    diff -u template.xml ${target}.xml
    rm -f /localvms/${target}.cow
    qemu-img create -b /localvms/$(basename ${PHD_VAR_vm_base}) -f qcow2 /localvms/${target}.cow
    virsh define ${target}.xml
    if [ $? != 0 ]; then exit 1; fi
    virsh start ${target}
    if [ $? != 0 ]; then exit 1; fi
    rm ${target}.xml.sed ${target}.xml
  fi
  
  sequence=$((sequence + 1))
done
